<template>
    <div>
        <SuperTable ref="table" path="/common/advert/index" :params="params" :columns="columns">
            <Button slot="header-left" type="primary" @click="showModal = true">新增广告</Button>
        </SuperTable>
        <Modal :title="form.id ? '编辑广告' : '新增广告'" v-model="showModal" :width="500" @on-cancel="handleCancel">
            <Alert type="warning">投放地区为空则代表所有地区都投放，如果投放地区重复，客户端会获取最新的一条广告；选择要跳转的项目后，请勿更改生成的链接，系统会自动配置跳转至APP项目页面地址</Alert>
            <Form ref="form" :model="form" :rules="rules" :label-width="80">
                <FormItem label="广告名称" prop="title">
                    <Input v-model="form.title" />
                </FormItem>
                <Row :gutter="20">
                    <Col span="10">
                        <FormItem label="广告图片" prop="img">
                            <ImageUpload v-model="form.img"></ImageUpload>
                        </FormItem>
                    </Col>
                    <Col span="10">
                        <div style="margin-top: 5px; color: #ccc">推荐尺寸比例：750*1334</div>
                    </Col>
                </Row>
                <FormItem label="广告位置" prop="position">
                    <Select v-model="form.position">
                        <Option :value="1">开屏广告</Option>
                    </Select>
                </FormItem>
                <FormItem label="链接地址" prop="url">
                    <Input v-model="form.url" placeholder="链接地址">
                        <Button type="info" slot="append" @click="handleOpenModal">跳转项目</Button>
                    </Input>
                </FormItem>
                <FormItem label="投放地区" prop="area_ids">
                    <Select v-model="form.area_ids" clearable multiple filterable>
                        <Option v-for="item in districtInfo" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem label="状态" prop="status">
                    <RadioGroup v-model="form.status">
                        <Radio :label="1">启用</Radio>
                        <Radio :label="0">禁用</Radio>
                    </RadioGroup>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button :disabled="submiting" @click="handleCancel">取消</Button>
                <Button type="primary" :loading="submiting" @click="handleSubmit">提交</Button>
            </div>
        </Modal>
        <Modal
            v-model="showProjectModal"
            title="选择项目"
            width="1200px"
            @on-cancel="handleCancelSelect"
        >
            <ProjectSelect ref="projectModal" :value="selectProject"></ProjectSelect>
            <div slot="footer">
                <Button @click="handleCancelSelect">取消</Button>
                <Button type="primary" @click="handleSelect">确认</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import SuperTable from '@/components/utils/super-table.vue';
import TableRows from '@/components/utils/table-rows.vue';
import ImageUpload from '@/components/form/image-upload.vue';
import ProjectSelect from '@/components/selector/project-select.vue';
export default {
    components: {
        SuperTable,
        TableRows,
        ImageUpload,
        ProjectSelect
    },
    data() {
        return {
            selectProject: [],
            showProjectModal: false,
            districtInfo: [],
            submiting: false,
            showModal: false,
            form: {
                id: '',
                title: '',
                img: '',
                position: 1,
                url: '',
                area_ids: [],
                status: 1,
            },
            rules: {
                title: [
                    {required: true, message: '请输入广告名称', trigger: 'blur'}
                ],
                img: [
                    {required: true, message: '请上传广告图片', trigger: 'change'}
                ],
                position: [
                    {required: true, type: 'number', message: '请选择所属广告位', trigger: 'change'}
                ]
            },
            params: {
                page: 1,
                pageSize: 10
            },
            columns: [
                {
                    title: '标题',
                    key: 'title'
                },
                {
                    title: '图片',
                    render: (h, params) => {
                        return h(TableRows, {
                            props: {
                                src: params.row.img || '/static/images/default_avatar.png'
                            }
                        })
                    }
                },
                {
                    title: '广告位置',
                    key: 'position_text'
                },
                {
                    title: '链接',
                    render: (h, params) => {
                        return h('a',{
                            attrs:{
                                target:'__blank',
                                href: params.row.url
                            }
                        }, params.row.url);
                    }
                },
                {
                    title: '投放地区',
                    render: (h, params) => {
                        return h('span', params.row.area_names ? params.row.area_names.join(',') : '');
                    }
                },
                {
                    title: '状态',
                    key: 'status_text'
                },
                {
                    title: '创建时间',
                    key: 'created_at'
                },
                {
                    title: '更新时间',
                    key: 'updated_at'
                },
                {
                    title: "操作",
                    align: "center",
                    key: "action",
                    width: 120,
                    render: (h, params) => {
                        return h("div", [
                            h("Button", {
                                props: {
                                    type: "success",
                                    size: "small"
                                },
                                on: {
                                    click: () => {
                                        this.showModal = true;
                                        this.form.id = params.row.id;
                                        this.form.title = params.row.title;
                                        this.form.img = params.row.img;
                                        this.form.position = params.row.position;
                                        this.form.url = params.row.url;
                                        this.form.area_ids = params.row.area_ids || [];
                                        this.form.status = params.row.status;
                                        if (params.row.url){
                                            this.handleSetProject();
                                        }
                                    }
                                }
                            }, "编辑"),
                            h("Button", {
                                style: {
                                    marginLeft: "5px"
                                },
                                props: {
                                    type: "error",
                                    size: "small"
                                },
                                on: {
                                    click: () => {
                                        this.handleDelete(params.row);
                                    }
                                }
                            }, "删除")
                        ])
                    }
                }
            ]
        };
    },
    mounted() {
        this.init();
    },
    methods: {
        init(){
            //获取地区
            this.$ajax.post('/areaApi/get_children', {id: 100000}).then(res => {
                this.districtInfo = res;
            }).catch(err => {
            })
        },
        handleSetProject() {
            let id = 0;
            if (this.form.url.indexOf('https://m.piaopiaodao.com/pages/goods/detail?id=') !== -1){
                let params = this.getUrlParams(this.form.url);
                id = params.id;
            }
            //获取项目详情
            this.$ajax.get('/project/read/'+id).then(res => {
                this.selectProject = res ? [res] : [];
            }).catch(err => {
            })
        },
        getUrlParams(url) {
            const regex = /[?&]([^=#]+)=([^&#]*)/g;
            let params = {};
            let match;
            while ((match = regex.exec(url))) {
                params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
            }
            return params;
        },
        handleOpenModal() {
            this.$refs.projectModal.init();
            this.showProjectModal = true;
        },
        handleCancelSelect() {
            this.$refs.projectModal.clear();
            this.showProjectModal = false;
        },
        handleSelect() {
            let res = this.$refs.projectModal.getCheckeds();
            this.selectProject = res;
            this.form.url = 'https://m.piaopiaodao.com/pages/goods/detail?id=' + res[0].id;
            this.handleCancelSelect();
        },
        handleDelete(row) {
            this.$Modal.confirm({
                title: "操作提示:",
                width: 320,
                content: `<p>您确定要删除广告‘${row.title}’吗?</p>`,
                onOk: () => {
                    const msg = this.$Message.loading({
                        content: '正在提交删除',
                        duration: 0
                    });
                    this.$ajax.delete('/common/advert/delete', {params: {ids: [row.id]}}).then(() => {
                        msg();
                        this.$Message.success('删除成功');
                        this.$refs.table.reload();
                    }).catch(err => {
                        msg();
                        this.$Message.error(err.message || '删除失败');
                    })
                }
            });
        },
        handleSubmit() {
            if(this.submiting) return false;
            this.$refs.form.validate((valid) => {
                if(valid) {
                    const { form } = this;
                    let params = {
                        title: form.title,
                        img: form.img,
                        position: form.position,
                        url: form.url,
                        area_ids: form.area_ids,
                        status: form.status,
                    }
                    this.submiting = true;
                    if (form.id) {
                        this.$ajax.put('/common/advert/update/'+form.id, params).then(res => {
                            this.$Message.success('编辑成功');
                            this.handleCancel();
                            this.$refs.table.reload();
                            this.submiting = false;
                        }).catch(err => {
                            this.submiting = false;
                            this.$Message.error(err.message || '提交失败');
                        })
                    }else{
                        this.$ajax.post('/common/advert/save', params).then(res => {
                            this.$Message.success('添加成功');
                            this.handleCancel();
                            this.$refs.table.init();
                            this.submiting = false;
                        }).catch(err => {
                            this.submiting = false;
                            this.$Message.error(err.message || '提交失败');
                        })
                    }
                }
            })
        },
        handleCancel() {
            this.showModal = false;
            setTimeout(() => {
                this.form.id = '';
                this.form.title = '';
                this.form.img = '';
                this.form.position = 1;
                this.form.url = '';
                this.form.area_ids = [];
                this.form.status = 1;
                this.selectProject = [];
            }, 300)
        }
    }
};
</script>